import requests
from django.template.defaultfilters import lower
from Common.loggers import Logger
from Common.yaml_util import *
from Common.getpath import *


class ApiRequest:
    def __init__(self, requst_data):
        self.requst_data = requst_data

    def send_get(self, url, headers, params):
        res = requests.get(url=url, headers=headers, data=params)
        return res

    def send_post(self, url, headers, params):
        res = requests.post(url=url, headers=headers, data=params)
        return res

    # request_data 需要传入yaml的request
    def run_main(self):
        request_data = self.requst_data
        url = YamlUtil(get_root_path() + "\\Configs\\HostConfig.yaml").read_yaml()[0]['url'] + request_data['url']
        print(url)
        method = request_data["method"]
        headers = request_data["headers"]
        params = request_data['params']
        print(headers)
        print(params)

        result = None
        if lower(method) == 'get':
            result = self.send_get(url=url, headers=headers, params=params)
            Logger().get_logger().info(str(result))
        elif lower(method) == 'post':
            result = self.send_post(url=url, headers=headers, params=params)
            Logger().get_logger().info(str(result))
        else:
            Logger().get_logger().info("method 错误")
        return result
